package com.cgwx.testservice.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cgwx.commonutils.result.Result;
import com.cgwx.springsecurity.annotation.Log;
import com.cgwx.springsecurity.enums.BusinessType;
import com.cgwx.testservice.entity.TestRecords;
import com.cgwx.testservice.entity.vo.TestRecordsExcelVo;
import com.cgwx.testservice.entity.vo.TestRecordsQueryVo;
import com.cgwx.testservice.service.TestRecordsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 测试记录 前端控制器
 * </p>
 *
 * @author GaoWei
 * @since 2023-11-25
 */

@Api(tags = "测试记录前端控制器")
@RestController
@RequestMapping("/test/testRecords")
@CrossOrigin
public class TestRecordsController {

    @Autowired
    private TestRecordsService testRecordsService;

//    添加测试记录
    @PreAuthorize("hasAuthority('bnt.testRecord.add')")
    @ApiOperation("添加测试记录")
    @PostMapping("addTestRecords")
    public Result addTestRecords(
            @ApiParam(name = "testRecords", value = "待添加的测试记录")
            @RequestBody TestRecords testRecords) {
        boolean is_Success = testRecordsService.save(testRecords);
        if(is_Success) {
            return Result.ok().data("message", "测试记录添加成功");
        } else {
            return Result.error().data("message", "测试记录添加失败");
        }
    }

//    删除测试记录
    @Log(title = "删除测试记录", businessType = BusinessType.TEST_RECORDS_DELETE)
    @PreAuthorize("hasAuthority('bnt.testRecord.remove')")
    @ApiOperation("删除测试记录")
    @DeleteMapping("removeTestRecords/{id}")
    public Result removeTestRecords(
            @ApiParam(name = "id", value = "待删除的测试记录id")
            @PathVariable Long id) {
        boolean is_Success = testRecordsService.removeById(id);
        if(is_Success) {
            return Result.ok().data("message", "测试记录删除成功");
        } else {
            return Result.error().data("message", "测试记录删除失败");
        }
    }

//    修改测试记录
    @Log(title = "修改测试记录", businessType = BusinessType.TEST_RECORDS_UPDATE)
    @ApiOperation("修改测试记录")
    @PostMapping("updateTestRecords")
    public Result updateTestRecords(
            @ApiParam(name = "testRecords", value = "待修改的测试记录")
            @RequestBody TestRecords testRecords) {
        boolean is_Success = testRecordsService.updateById(testRecords);
        if(is_Success) {
            return Result.ok().data("message", "测试记录修改成功");
        } else {
            return Result.error().data("message", "测试记录修改失败");
        }
    }

//    条件分页查询测试记录列表
    @ApiOperation("条件分页查询测试记录列表")
    @GetMapping("{page}/{limit}")
    public Result getTestRecordsList(
            @ApiParam(name = "page", value = "当前页")
            @PathVariable Long page,
            @ApiParam(name = "limit", value = "每页显示的记录数")
            @PathVariable Long limit,
            @ApiParam(name = "testRecordsQueryVo", value = "待查询的测试记录条件Vo")
                    TestRecordsQueryVo testRecordsQueryVo) {
        //创建page对象
        Page<TestRecords> pageParam = new Page<>(page,limit);
        //调用service方法
        IPage<TestRecords> pageModel = testRecordsService.selectPage(pageParam,testRecordsQueryVo);
        return Result.ok().data("pageModel",pageModel);
    }

//    根据ID查询测试记录
    @ApiOperation("根据id查询测试记录")
    @GetMapping("getTestRecords/{id}")
    public Result getTestRecords(
            @ApiParam(name = "id", value = "待查询的测试记录id")
            @PathVariable String id) {
        TestRecords testRecords = testRecordsService.getById(id);
        return Result.ok().data("testRecords",testRecords);
    }

//    下载测试记录，测试记录形成Excel表格
    @Log(title = "下载测试记录Excel", businessType = BusinessType.TEST_RECORDS_EXPORT)
    @ApiOperation(value = "下载测试记录Excel")
    @PostMapping("downloadTestRecords/{id}")
    public void downloadTestRecords(
            @ApiParam(name = "id", value = "待下载的测试记录id")
            @PathVariable String id,
            HttpServletResponse response) throws IOException {
    //    根据id查询测试记录
        TestRecords testRecords = testRecordsService.getById(id);
    //    设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
    //    这里URLEncoder.encode可以防止中文乱码 当然和easyExcel没有关系
        String fileName = URLEncoder.encode(testRecords.getSatelliteType() + "-" +
                testRecords.getSatelliteName() + "-" + testRecords.getComponentsName() + "测试记录", StandardCharsets.UTF_8);
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
    //    封装数据
        TestRecordsExcelVo testRecordsExcelVo = new TestRecordsExcelVo();
        BeanUtils.copyProperties(testRecords,testRecordsExcelVo);
        List<TestRecordsExcelVo> testRecordsExcelVoList = new ArrayList<>();
        testRecordsExcelVoList.add(testRecordsExcelVo);
    //        写入Excel
        EasyExcel.write(response.getOutputStream(), TestRecordsExcelVo.class).sheet("测试记录").doWrite(testRecordsExcelVoList);
    }
}

